package io.boot.modules.activiti.service.impl;

import io.boot.common.utils.PageUtils;
import io.boot.modules.activiti.dto.Pending;
import io.boot.modules.activiti.service.PendingService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author kyson
 * @date 2020/04/20 11:34
 */
@Service("PendingServiceImpl")
public class PendingServiceImpl implements PendingService {

    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;


    @Override
    public PageUtils queryPage(Map<String, Object> params, String userName) {
        Integer page=Integer.valueOf(params.get("page").toString());
        Integer limit=Integer.valueOf(params.get("limit").toString());
        List<Task> tasks =taskService.createTaskQuery().taskCandidateUser(userName).orderByTaskPriority().desc().orderByTaskCreateTime().desc().list();
        List<Pending>  upComingList=new ArrayList<>();
        for (Task task:tasks) {
            Pending pending=new Pending();
//            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).includeProcessVariables().singleResult();
//            pending.setReferee(processInstance.getProcessVariables().get("createBy")!=null?processInstance.getProcessVariables().get("createBy").toString():"");
            pending.setId(task.getId());
            pending.setUpUser(task.getAssignee());
            pending.setCreateTime(task.getCreateTime());
            List<String> processDefinitionIds= Arrays.asList(task.getProcessDefinitionId().split(":"));
            pending.setProcessName(processDefinitionIds.get(0));
            pending.setProcessVersion(processDefinitionIds.get(1));
            pending.setUpName(task.getName());
            pending.setType(task.isSuspended());
            pending.setAssignee(task.getAssignee());
            pending.setInstanceId(task.getProcessInstanceId());
            upComingList.add(pending);
        }
        PageUtils pages =new PageUtils(upComingList,Integer.valueOf(taskService.createTaskQuery().count()+""),page,limit);
        return pages;
    }
}
